package controllers_admin

import (
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"manageCrontab/crontab"
	"manageCrontab/db"
	"manageCrontab/lib"
	"manageCrontab/models"
	"strings"
)

type TaskController struct {
}

func (c *TaskController) BeforeActivation(b mvc.BeforeActivation) {
	// httpMethod 参数一定要全大写,  找不到路由，请注意大小写问题
	b.Handle("GET", "/taskList", "ListPage")
	b.Handle("GET", "/editTask/{taskId}", "EditTaskPage").Name = "editTaskPage"
	b.Handle("POST", "/taskList/", "List").Name = "taskList"
	b.Handle("POST", "/editTask", "EditTask").Name = "editTask"
	b.Handle("POST", "/taskInfo", "TaskInfo").Name = "taskInfo"
	b.Handle("POST", "/delTask", "DelTask").Name = "delTask"
	b.Handle("POST", "/startTask", "StartTask").Name = "startTask"
	b.Handle("POST", "/stopTask", "StopTask").Name = "stopTask"
}

func (c *TaskController) StopTask(ctx iris.Context) string {
	taskId := ctx.PostValue("TaskId")
	task := models.Task{}
	db.GetDB().Model(&models.Task{}).Where("task_id=?", taskId).First(&task)
	//if err := db.GetDB().Model(&models.Task{}).Where("task_id=?", taskId).Update("task_status", 2).Error; err != nil {
	//	return lib.GetJsonResponse(models.REQUEST_FAIL, nil, "操作失败")
	//}
	if err := crontab.StopTaskById(task, true); err != nil {
		return lib.GetJsonResponse(models.REQUEST_FAIL, nil, "操作失败")
	}
	return lib.GetJsonResponse(models.REQUEST_SUCCESS, nil, "")
}

func (c *TaskController) StartTask(ctx iris.Context) string {
	taskId := ctx.PostValue("TaskId")
	if err := db.GetDB().Model(&models.Task{}).Where("task_id=?", taskId).Where("task_status=2").Update("task_status", 0).Error; err != nil {
		return lib.GetJsonResponse(models.REQUEST_FAIL, nil, "操作失败")
	}
	return lib.GetJsonResponse(models.REQUEST_SUCCESS, nil, "")
}

func (c *TaskController) Test() string {
	data := []map[string]interface{}{}
	for i := 1; i < 10; i++ {
		data_ := map[string]interface{}{}
		data_["name"] = "abcd"
		data_["description"] = "fghi"
		data = append(data, data_)
	}
	return lib.GetJsonResponse(models.REQUEST_SUCCESS, data, "AAAAA")
}

// @title 列表页面
func (c *TaskController) ListPage() mvc.Result {
	return mvc.View{
		Name: "task_list.html",
	}
}

// @title 任务列表
// @note 分页查询，条件查询，排序
func (c *TaskController) List(ctx iris.Context) string {
	page, _ := ctx.PostValueInt("page")
	limit, _ := ctx.PostValueInt("limit")
	runStatus, _ := ctx.PostValueInt("RunStatus")
	taskName := ctx.PostValue("TaskName")
	page = lib.If(page > 0, page, 1).(int)
	limit = lib.If(limit > 0, limit, lib.GetCustomParam("limit")).(int)
	pageIndex := (page - 1) * limit
	data := map[string]interface{}{}
	taskList := []models.Task{}
	find := db.GetDB().Model(models.Task{})
	if runStatus > -1 {
		find = find.Where("run_status=?", runStatus)
	}
	if taskName != "" {
		find = find.Where("task_name like ? ", "%"+taskName+"%")
	}
	find.Where("is_valid=1").
		Order("created_at desc").
		Offset(pageIndex).
		Limit(limit).Find(&taskList)
	count := 0
	db.GetDB().Model(models.Task{}).Where("is_valid=1").Count(&count)
	data["count"] = count
	data["taskList"] = taskList
	return lib.GetJsonResponse(models.REQUEST_SUCCESS, data, "")
}

// @title 添加修改任务页面
func (c *TaskController) EditTaskPage(taskId string) mvc.Result {
	// 添加
	if taskId == "0" {
		taskId = ""
	}
	return mvc.View{
		Name: "task_edit.html",
		Data: map[string]interface{}{"taskId": taskId},
	}
}

// @title 添加编辑
func (c *TaskController) EditTask(ctx iris.Context) string {
	task := models.Task{}
	task.TaskName = ctx.PostValue("TaskName")
	task.TaskDescript = ctx.PostValue("TaskDescript")
	task.TaskSpec = ctx.PostValue("TaskSpec")
	task.TaskType = ctx.PostValue("TaskType")
	task.TaskData = ctx.PostValue("TaskData")
	taskId := ctx.PostValue("TaskId")
	// 判断是新增还是修改
	if taskId == "" {
		task.TaskStatus = 0
		task.RunCount = 0
		task.TaskId = lib.GendXid()
		if err := db.GetDB().Create(&task).Error; err != nil {
			return lib.GetJsonResponse(models.REQUEST_FAIL, nil, "添加失败")
		}
	} else {
		if err := db.GetDB().Model(&models.Task{}).Where("task_id=?", taskId).Updates(task).Error; err != nil {
			return lib.GetJsonResponse(models.REQUEST_FAIL, nil, "修改失败")
		}
	}
	return lib.GetJsonResponse(models.REQUEST_SUCCESS, nil, "保存成功")
}

// @title 获取任务信息
func (c *TaskController) TaskInfo(ctx iris.Context) string {
	task := models.Task{}
	taskId := ctx.PostValue("TaskId")
	db.GetDB().Where("task_id=?", taskId).First(&task)
	return lib.GetJsonResponse(models.REQUEST_SUCCESS, task, "")
}

// @title delTask
// @note 注意角色权限，确定修改表字段，没有其他操作
func (c *TaskController) DelTask(ctx iris.Context) string {
	task := models.Task{}
	task.IsValid = 0
	taskIds_ := ctx.PostValue("TaskIds")
	taskIds := strings.Split(taskIds_, ",")
	tx := db.GetDB().Begin()
	//defer func() {
	//	if r := recover(); r != nil {
	//		tx.Rollback()
	//	}
	//}()
	for _, taskId := range taskIds {
		// 事务使用updates()方法更新表，不执行更新操作
		if err := tx.Model(&models.Task{}).Where("task_id=?", taskId).Update("is_valid", 0).Error; err != nil {
			fmt.Println(err)
			tx.Rollback()
			return lib.GetJsonResponse(models.REQUEST_FAIL, nil, "删除失败")
		}
	}
	tx.Commit()
	return lib.GetJsonResponse(models.REQUEST_SUCCESS, nil, "删除成功")
}
